import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../viewmodel/gt_mvvm_base_view_model.dart';
import 'gt_mvvm_base_view.dart';

/// MVVM基础视图层
abstract class GTMVVMCustomView<T extends GTMVVMBaseViewModel> extends ConsumerStatefulWidget with GTMVVMBaseView {
  late T viewModel = createViewModel();

  GTMVVMCustomView({super.key});

  Widget build(BuildContext context, WidgetRef ref) {
    viewModel.inject(ref);
    return buildPage(context);
  }

  void init();

  void dispose();

  /// 创建ViewModel
  T createViewModel();

  Widget buildPage(BuildContext context);

  @override
  createState() {
    return GTMVVMViewState();
  }
}

class GTMVVMViewState<T extends GTMVVMCustomView> extends ConsumerState<T> {
  @override
  WidgetRef get ref => context as WidgetRef;

  @override
  Widget build(BuildContext context) {
    return widget.build(context, ref);
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      widget.getRouteParams(context);
      widget.init();
      widget.viewModel.init();
    });
  }

  @override
  void dispose() {
    super.dispose();
    widget.dispose();
    widget.viewModel.dispose();
  }
}
